# -*- coding:utf-8 -*-
from com.zzh.utils.dbUtils import MysqlUtils
from com.zzh.utils.jsonUtils_v2.table2Json_Chen import Table2Json
from simsearch import Getsimwords
from com.zzh.utils.requestFieldMapDBField import fieldMap_Chen
from com.zzh.utils.pagingUtils import MyPaging
from com.zzh.utils.sqlUtils.SqlUtils import SqlUtils

class BigSearch(object):
    def __init__(self):
        self.conn = MysqlUtils.get_mysql_connections_v2()

    def itemBigSearch(self, keyword):
        simKeyword = Getsimwords(keyword)
        # print simKeyword[0][0], simKeyword[1][0], simKeyword[2][0]
        word = '%' + keyword + '%'
        word0 = '%' + simKeyword[0][0] + '%'
        word1 = '%' + simKeyword[1][0] + '%'
        word2 = '%' + simKeyword[2][0] + '%'
        sql = "select * from view_item WHERE item_title LIKE %s OR item_title LIKE %s OR item_title LIKE %s OR item_title LIKE %s "
        cur = self.conn.cursor()
        try:
            rs = cur.execute(sql, [word, word0, word1, word2])
        except:
            return -200, 0
        rsJson = None
        if rs:
            rsList = cur.fetchall()
            rsJson = Table2Json.view_item_list_to_json(rsList)
        cur.close()
        self.conn.close()
        return rsJson, rs

    def itemBigSearchAndCondition(self, **kwargs):
        pageIndex = kwargs['pageIndex']
        pageSize = kwargs['pageSize']
        conditions = kwargs['conditions']
        multiSort = kwargs['multiSort']
        keyword=kwargs['keyword']

        # 获取对应的映射字典
        fieldMap = fieldMap_Chen.viewItemFieldMap
        whereSentence = SqlUtils.getOption(conditions, fieldMap)
        cur = self.conn.cursor()
        simKeyword = Getsimwords(keyword)
        # print simKeyword[0][0], simKeyword[1][0], simKeyword[2][0]
        word = '%' + keyword + '%'
        word0 = '%' + simKeyword[0][0] + '%'
        word1 = '%' + simKeyword[1][0] + '%'
        word2 = '%' + simKeyword[2][0] + '%'
        if multiSort:
            # 排序拼接
            sortRule = SqlUtils.getSortRule(multiSort, fieldMap)
            sql = "select * from view_item WHERE item_title LIKE %s OR item_title LIKE %s OR item_title LIKE %s OR item_title LIKE %s AND "+whereSentence+ " ORDER BY " + sortRule
        else:
            sql = "select * from view_item WHERE item_title LIKE %s OR item_title LIKE %s OR item_title LIKE %s OR item_title LIKE %s AND " + whereSentence

        try:
            rs = cur.execute(sql, [word, word0, word1, word2])
        except:
            return -200, 0
        rsJson = None
        if rs:
            rsList = cur.fetchall()
            rsList= MyPaging().getPage(rs, pageIndex, pageSize, rsList)
            rsJson = Table2Json.view_item_list_to_json(rsList)
        cur.close()
        self.conn.close()
        return rsJson, rs